cc.Class({
    extends: cc.Component,

    properties: {
        // lblRoomNo:{
        //     default:null,
        //     type:cc.Label
        // },
        // foo: {
        //    default: null,
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
        _seats:[],
        _seats2:[],
        _gpsSeats:[],
        _timeLabel:null,
        _voiceMsgQueue:[],
        _playingSeat:null,
        _lastPlayTime:null,
        _gps:null,
        _gamecount:null,
        _zhezhao:null
    },

    // use this for initialization
    onLoad: function () {
        console.log("MjRoomOnLoad");
        // cc.vv.MjRoom=this;
        if(cc.vv == null){
            return
        };
        this.initView();
        this.initSeats();
        this.initEventHandlers()
    },
    
    initView:function(){
        var prepare = this.node.getChildByName("prepare");
        var seats = prepare.getChildByName("seats");
       
        for(var i = 0; i < seats.childrenCount; ++i){
            this._seats.push(seats.children[i].getComponent("Seat"))
        };

        // this._gps=this.node.getChildByName("gps");
        // cc.vv.utils.addClickEvent(this._gps,this.node,"MjRoom","onCloseGpsClicked");
        // var gpsSeats = this._gps.getChildByName("seats");
        // for(var i = 0; i < gpsSeats.children.length; ++i){
        //     this._gpsSeats.push(gpsSeats.children[i].getComponent("Seat"))
        // };
        this.refreshBtns();
        
        this.lblRoomNo = cc.find("Canvas/infobar/Z_room_txt/roomId").getComponent(cc.Label);
        
        var infobar=this.node.getChildByName("infobar");
        this._timeLabel = infobar.getChildByName("time").getComponent(cc.Label);
        this.lblRoomNo.string = cc.vv.gameNetMgr.roomId;
        this._gamecount = infobar.getChildByName('gamecount').getComponent(cc.Label);
        this._gamecount.string = "第"+cc.vv.gameNetMgr.numOfGames + "/" + cc.vv.gameNetMgr.maxNumOfGames+"局";
        var gameChild = this.node.getChildByName("game");
        var sides = ["myself","right","up","left"];
        for(var i = 0; i < sides.length; ++i){
            var sideNode = gameChild.getChildByName(sides[i]);
            var seat = sideNode.getChildByName("seat");
            this._seats2.push(seat.getComponent("Seat"))
        };
        this._zhezhao=gameChild.getChildByName("qiangZhezhao");
        // var gpsBt = this.node.getChildByName("gpsbtn");
        // if(gpsBt){
        //     gpsBt.active = cc.vv.replayMgr.isReplay() == false;
        //     cc.vv.utils.addClickEvent(gpsBt,this.node,"MjRoom","onGpsClicked")
        // };
        // var fanhuiBt = this._gps.getChildByName("fanhui");
        // if(fanhuiBt){
        //     cc.vv.utils.addClickEvent(fanhuiBt,this.node,"MjRoom","onCloseGpsClicked")
        // };
        var btnWechat = cc.find("Canvas/prepare/btnWeichat");
        if(btnWechat){
            cc.vv.utils.addClickEvent(btnWechat,this.node,"MjRoom","onBtnWeichatClicked")
        };
         
        var btnReady = cc.find("Canvas/prepare/btnReady");
        if(btnReady){
            cc.vv.utils.addClickEvent(btnReady,this.node,"MjRoom","onBtnReadyClicked")
        };
        var btnBack = cc.find("Canvas/prepare/btnBack");
        if(btnBack){
            cc.vv.utils.addClickEvent(btnBack,this.node,"MjRoom","onBtnBackClicked")
        };
        var btnDissolve = cc.find("Canvas/prepare/btnDissolve");
        if(btnDissolve){
            cc.vv.utils.addClickEvent(btnDissolve,this.node,"MjRoom","onBtnDissolveClicked")
        };
        var btnExit = cc.find("Canvas/prepare/btnExit");
        if(btnExit){
            cc.vv.utils.addClickEvent(btnExit,this.node,"MjRoom","onBtnExit")
        };
        var btn_settings = cc.find("Canvas/btn_settings");
        if(btn_settings){
            cc.vv.utils.addClickEvent(btn_settings,this.node,"MjRoom","onBtnSettingsClicked")
        };
        // 预加载大厅场景
        setTimeout(function(){
            cc.director.preloadScene("mjhall", function () {
                cc.log("mjhall preloaded")
            })
        },2000)
        // 第一次进入房间才显示
        // if (cc.vv.gameNetMgr.gamestate==""&&cc.vv.gameNetMgr.numOfGames<1) {
        //     this.onGpsClicked()
        // }
    },
    
    refreshBtns:function(){
        var prepare = this.node.getChildByName("prepare");
        var btnExit = prepare.getChildByName("btnExit");
        var btnDispress = prepare.getChildByName("btnDissolve");
        var btnWeichat = prepare.getChildByName("btnWeichat");
        var btnReady = prepare.getChildByName("btnReady");
        var btnBack = prepare.getChildByName("btnBack");
        var isIdle = cc.vv.gameNetMgr.numOfGames == 0;
        
        btnExit.active = !cc.vv.gameNetMgr.isOwner() && isIdle;
        btnWeichat.active = isIdle;
        btnReady.active = false;
        btnBack.active = isIdle&&cc.vv.gameNetMgr.isOwner();
        btnDispress.active = cc.vv.gameNetMgr.isOwner() && isIdle
    },
    
    initEventHandlers:function(){
        var self = this;
        this.node.on('new_user',function(data){
            console.log("new_user/MjRoom");
            self.initSingleSeat(data.detail)
        });
        
        this.node.on('user_state_changed',function(data){
            console.log("user_state_changed");
            // 大结算时不刷新坐席以免提前显示扣分
            if (!cc.vv.gameNetMgr.isEnd) {
                self.initSingleSeat(data.detail)
            }
        });
        this.node.on('user_ready_changed',function(data){
            console.log("user_ready_changed");
            var data=data.detail;
            var index = cc.vv.gameNetMgr.getLocalIndex(data.seatindex);
            self._seats[index].setReady(data.ready);
            self._seats2[index].setReady(data.ready)
        });
        this.node.on('game_begin',function(data){
            console.log("game_begin/MjRoom");
            self.refreshBtns();
            self.initSeats()
        });
        this.node.on('game_dingzhuang',function(data){
            console.log("game_dingzhuang/MjRoom",data.detail);
            var data=data.detail;
            // 分抢庄模式和轮庄模式
            if (cc.vv.gameNetMgr.conf.bankertype==0) {
                console.log("轮庄模式");
                var localIndex=cc.vv.gameNetMgr.getLocalIndex(data.zhuang);
                if (cc.vv.gameNetMgr.numOfGames%2==1) {
                    cc.vv.audioMgr.playSFX("zhuang.mp3");
                    self._seats2[localIndex].setZhuang(true,true)
                }else{
                    self._seats2[localIndex].setZhuang(true)
                }
            }else if (cc.vv.gameNetMgr.numOfGames%2==0) {
                console.log("抢庄双数局");
                var localIndex=cc.vv.gameNetMgr.getLocalIndex(data.zhuang);
                self._seats2[localIndex].setZhuang(true)
            }else{
                console.log("抢庄模式");
                // 先做动画，最后显示定庄
                // 开启黑遮罩
                self._zhezhao.active=true;
                    // 先获取之前谁选了抢庄
                var seats=cc.vv.gameNetMgr.seats;
                // 抢庄坐席
                var qiangArr=[];
                // 不抢庄坐席
                var buqiangArr=[];
                // 分数最多
                var maxScore=0;
                for (var i = 0; i < seats.length; i++) {
                    if (seats[i].qiangzhuang==1) {
                        qiangArr.push(seats[i].seatindex)
                    }else{
                        buqiangArr.push(seats[i].seatindex);
                        // 开坐席遮罩
                        var index = cc.vv.gameNetMgr.getLocalIndex(seats[i].seatindex);
                        self._seats2[index].node.getChildByName("zhezhao").active=true
                    };
                    if (seats[i].score>maxScore) {
                        maxScore=seats[i].score
                    }
                };
                console.log("参与抢庄坐席",qiangArr,"当前最大分",maxScore);
                if (qiangArr.length==0) {
                    // 没人抢时分数最多的坐庄（有多个话则在里面随机）
                    for (var i = 0; i < seats.length; i++) {
                        if (seats[i].score>=maxScore) {
                            qiangArr.push(seats[i].seatindex)
                        }
                    };
                    console.log("都没人抢庄，重新获取最大分坐席作为抢庄坐席",qiangArr)
                };
                if (qiangArr.length==1) {
                    // 一个人抢时没有抢庄动画
                    var localIndex=cc.vv.gameNetMgr.getLocalIndex(data.zhuang);
                    cc.vv.audioMgr.playSFX("zhuang.mp3");
                    self._seats2[localIndex].setZhuang(true,true);
                    setTimeout(function(){
                        self.node.emit("game_jiaofen");
                    },1000);
                    self._zhezhao.active=false;
                    // 关坐席遮罩
                    for (var i = 0; i < buqiangArr.length; i++) {
                        var index = cc.vv.gameNetMgr.getLocalIndex(buqiangArr[i]);
                        self._seats2[index].node.getChildByName("zhezhao").active=false
                    };
                    return
                };
                // 参与随机的坐席
                // var qiangArr=[0,1,2,3];
                // 控制次数
                var numCount=0;
                // 随机庄下标
                var Index=0;
                var fn=function(){
                    numCount++;
                    if (Index>qiangArr.length-1) {
                        Index=0
                    };
                    var localIndex=cc.vv.gameNetMgr.getLocalIndex(qiangArr[Index]);
                    if (numCount>10&&qiangArr[Index]==data.zhuang) {
                        console.log("抢庄结束");
                        cc.vv.audioMgr.playSFX("zhuang.mp3");
                        // 做个延时无缝衔接
                        self._seats2[localIndex].setZhuang(true);
                        setTimeout(function(){
                            self._seats2[localIndex].setZhuang(true,true);
                            // 结束才执行叫分
                            setTimeout(function(){
                                self.node.emit("game_jiaofen")
                            },1000)
                        },300);
                        self._zhezhao.active=false;
                        for (var i = 0; i < buqiangArr.length; i++) {
                            var index = cc.vv.gameNetMgr.getLocalIndex(buqiangArr[i]);
                            self._seats2[index].node.getChildByName("zhezhao").active=false
                        }
                    }else{
                        Index++;
                        self._seats2[localIndex].setZhuang(true);
                        // 次数够后到指定庄时停止
                        setTimeout(function(){
                            self._seats2[localIndex].setZhuang(false);
                            fn()
                        },200)
                    }
                };
                fn()
            }
        });
        // 结算翻盘结束才刷新坐席
        this.node.on('game_over_initseats',function(){
            console.log("game_over_initseats/MjRoom");
            self.initSeatsScore()
        });
        // this.node.on('reconnectInit',function(data){
        //     console.log("reconnectInit/MjRoom",data.detail);
        //     self.initSeats()
        // });
        this.node.on('game_num',function(data){
            self._gamecount.string = "第"+cc.vv.gameNetMgr.numOfGames + "/" + cc.vv.gameNetMgr.maxNumOfGames+"局"
        });
        this.node.on('voice_msg',function(data){
            var data = data.detail;
            self._voiceMsgQueue.push(data);
            self.playVoice()
        });
        
        this.node.on('chat_push',function(data){
            var data = data.detail;
            var idx = cc.vv.gameNetMgr.getSeatIndexByID(data.sender);
            var localIndex = cc.vv.gameNetMgr.getLocalIndex(idx);
            self._seats[localIndex].chat(data.content);
            self._seats2[localIndex].chat(data.content);
        });
        
        this.node.on('quick_chat_push',function(data){
            var data = data.detail;
            var seat=cc.vv.gameNetMgr.getSeatByID(data.sender);
            var localIndex = cc.vv.gameNetMgr.getLocalIndex(seat.seatindex);
            
            var index = data.content;
            var info = cc.vv.chat.getQuickChatInfo(index);
            self._seats[localIndex].chat(info.content);
            self._seats2[localIndex].chat(info.content);
            
            cc.vv.audioMgr.playSFX(info.sound,seat.sex)
        });
        
        this.node.on('emoji_push',function(data){
            var data = data.detail;
            var idx = cc.vv.gameNetMgr.getSeatIndexByID(data.sender);
            var localIndex = cc.vv.gameNetMgr.getLocalIndex(idx);
            self._seats[localIndex].emoji(data.content);
            self._seats2[localIndex].emoji(data.content)
        });
    },
    // 单一刷新坐席分数和扣分
    initSeatsScore:function(){
        console.log("initSeatsScore");
        var seats = cc.vv.gameNetMgr.seats;
        for(var i = 0; i < seats.length; ++i){
            var index = cc.vv.gameNetMgr.getLocalIndex(seats[i].seatindex);
            this._seats2[index].setInfo(seats[i].name,seats[i].score,false);
            this._seats2[index].setReady(seats[i].ready);
            // 扣分显示
            this._seats2[index].setKoufen(seats[i].koufen)
        };
    },
    // 刷新坐席
    initSeats:function(isplaying){
        console.log("initSeats");
        var seats = cc.vv.gameNetMgr.seats;
        for(var i = 0; i < seats.length; ++i){
            this.initSingleSeat(seats[i])
        };
        // 游戏未准备则显示准备按钮
        var btnReady=this.node.getChildByName("prepare").getChildByName("btnReady");
        if(!seats[cc.vv.gameNetMgr.seatIndex].ready){
            btnReady.active=true
        }else{
            btnReady.active=false
        }
    },
    // 刷新单个坐席
    initSingleSeat:function(seat){
        console.log("initSingleSeat",seat);
        var index = cc.vv.gameNetMgr.getLocalIndex(seat.seatindex);
        var isOffline = !seat.online;
        var isZhuang = false;
        var isFangzhu=false;
        if (seat.seatindex == cc.vv.gameNetMgr.button) {isZhuang=true};
        if (seat.seatindex==0) {isFangzhu=true};
        
        // 准备座位
        this._seats[index].setInfo(seat.name,seat.score,false);
        this._seats[index].setFangzhu(isFangzhu);
        this._seats[index].setReady(seat.ready);
        this._seats[index].setOffline(isOffline);
        this._seats[index].setID(seat.userid);
        this._seats[index].voiceMsg(false);
        // 游戏座位
        this._seats2[index].setInfo(seat.name,seat.score,false);
        this._seats2[index].setZhuang(isZhuang);
        this._seats2[index].setReady(seat.ready);
        this._seats2[index].setFangzhu(isFangzhu);
        this._seats2[index].setOffline(isOffline);
        this._seats2[index].setID(seat.userid);
        this._seats2[index].voiceMsg(false);
        // 扣分显示
        this._seats2[index].setKoufen(seat.koufen)

        // this._gpsSeats[index].setInfo(seat.name);
        // this._gpsSeats[index].setID(seat.userid);

        // if (!cc.vv.replayMgr.isReplay()) {
        //     // 第一次进入房间才显示
        //     if (cc.vv.gameNetMgr.gamestate==""&&cc.vv.gameNetMgr.numOfGames<1) {
        //         this.onGpsClicked()
        //     }
        // };
    },
    // GPS按钮点击
    onGpsClicked:function(){
        console.log("onGpsClicked");
        this._gps.active=true;
        var juliNode=this._gps.getChildByName("juli");
        var shuju=cc.vv.gameNetMgr.location;
        if (shuju==[]||!shuju) {
            shuju=[-1,-1,-1,-1,-1,-1]
        };
        var ips=cc.vv.gameNetMgr.ipsResult;
        var shunxu=[[0,1,2,3,4,5],[3,4,0,5,1,2],[5,1,3,2,4,0],[2,4,5,0,1,3]];
        var seatIndex=cc.vv.gameNetMgr.seatIndex;
        shunxu=shunxu[seatIndex];
        for (var i = 0; i < ips.length; i++) {
            var juli=juliNode.children[i];
            var shujuIndex=shunxu[i];
            var gpsjuli=shuju[shujuIndex];
            var ipsResult=ips[shujuIndex];
            console.log("gpsjuli",gpsjuli,"ipsResult",ipsResult);
            if (ipsResult) {
                gpsjuli="IP相同";
                juli.getComponent(cc.Label).string=gpsjuli;
                juli.color=new cc.Color(255, 0, 0);
                continue
            }else{
                if (gpsjuli==-1) {
                    gpsjuli="未知"
                }else if (gpsjuli<100) {
                    gpsjuli="百米内"
                }else if(gpsjuli<1000){
                    gpsjuli="一公里内"
                }else if(gpsjuli>1000){
                    gpsjuli="超过一公里"
                }else{
                    gpsjuli="未知"
                }
            };
            juli.getComponent(cc.Label).string=gpsjuli;
            juli.color=new cc.Color(244, 223, 138)
        }
    },
    onCloseGpsClicked:function(){
        console.log("onCloseGpsClicked");
        if (this._gps.active) {
            this._gps.active=false
        }
    },
    onBtnSettingsClicked:function(){
        console.log("onBtnSettingsClicked");
        cc.vv.popupMgr.showSettings() 
    },
    onBtnReadyClicked:function(event){
        console.log("onBtnReadyClicked");
        cc.vv.net.send("ready");
        event.target.active=false
    },
    onBtnBackClicked:function(){
        console.log("onBtnBackClicked");
        cc.vv.alert.show("返回大厅","返回大厅房间仍会保留，快去邀请大伙来玩吧！",function(){
            cc.director.loadScene("mjhall")
        },true)
    },
    
    // onBtnChatClicked:function(){
        
    // },
    
    onBtnWeichatClicked:function(){
        var wanfa = cc.vv.gameNetMgr.getWanfa();
        var wanfaArr = wanfa.split(" ");
        // var type = wanfaArr.shift();
        var wanfaStr = wanfaArr.join(",");
        var renshu=0;
        for (var i = 0; i < cc.vv.gameNetMgr.seats.length; i++) {
            if (cc.vv.gameNetMgr.seats[i].name!="") {
                renshu++
            } 
        };
        var num=["一","二","三","四"];
        var str="";
        if (renshu<4) {
            str=num[renshu-1]+"缺"+num[4-renshu-1]
        };
        var culbstr="";
        if (cc.vv.gameNetMgr.clubid) {
            culbstr=cc.vv.gameNetMgr.clubname+"ID:"+cc.vv.gameNetMgr.clubid
        };
        cc.vv.anysdkMgr.share("天地人和"+",房号:" + cc.vv.gameNetMgr.roomId+str+culbstr,wanfaStr,"haoyou")
    },
    
    onBtnDissolveClicked:function(){
        cc.vv.alert.show("解散房间","解散房间不扣房卡，是否确定解散？",function(){
            cc.vv.net.send("dispress") 
        },true)
    },
    
    onBtnExit:function(){
        cc.vv.net.send("exit")
    },
    
    playVoice:function(){
        if(this._playingSeat == null && this._voiceMsgQueue.length){
            // console.log("playVoice2");
            var data = this._voiceMsgQueue.shift();
            var idx = cc.vv.gameNetMgr.getSeatIndexByID(data.sender);
            var localIndex = cc.vv.gameNetMgr.getLocalIndex(idx);
            this._playingSeat = localIndex;
            this._seats[localIndex].voiceMsg(true);
            this._seats2[localIndex].voiceMsg(true);
            
            var msgInfo = JSON.parse(data.content);
            
            var msgfile = "voicemsg.amr";
            // console.log(msgInfo.msg.length);
            cc.vv.voiceMgr.writeVoice(msgfile,msgInfo.msg);
            cc.vv.voiceMgr.play(msgfile);
            this._lastPlayTime = Date.now() + msgInfo.time
        }
    },
    
    // called every frame, uncomment this function to activate update callback
    update: function (dt) {
        var minute = Math.floor(Date.now()/1000/60);
        if (this._timeLabel) {
            if(this._lastMinute != minute){
                this._lastMinute = minute;
                var date = new Date();
                var n = date.getFullYear();
                var y = date.getMonth()+1;
                y = y < 10? "0"+y:y;
                var d = date.getDate();
                d = d < 10? "0"+d:d;
                var h = date.getHours();
                h = h < 10? "0"+h:h;
                var m = date.getMinutes();
                m = m < 10? "0"+m:m;
                this._timeLabel.string = n+"/"+y + "/" + d +"   "+ h + ":" + m ;  
            }
        };
        if(this._lastPlayTime != null){
            if(Date.now() > this._lastPlayTime + 200){
                this.onPlayerOver();
                this._lastPlayTime = null 
            }
        }else{
            this.playVoice()
        }
    },
    
        
    onPlayerOver:function(){
        cc.vv.audioMgr.resumeAll();
        // console.log("onPlayCallback:" + this._playingSeat);
        var localIndex = this._playingSeat;
        this._playingSeat = null;
        this._seats[localIndex].voiceMsg(false);
        this._seats2[localIndex].voiceMsg(false)
    },
    
    onDestroy:function(){
        cc.vv.voiceMgr.stop()
//        cc.vv.voiceMgr.onPlayCallback = null;
    }
});
